package com.faithnmn.utils.core;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.faithnmn.utils.core.callbacks.GotConfigurationsCallback;
import com.faithnmn.utils.core.callbacks.GotNotificationsCallback;
import com.faithnmn.utils.core.model.Configurations;
import com.faithnmn.utils.core.model.Notification;
import com.faithnmn.utils.core.network.NetworkExecutor;
import com.faithnmn.utils.core.utils.Constants;
import com.faithnmn.utils.core.utils.DummyAlg;
import com.faithnmn.utils.core.utils.Utils;
import com.volley.Response;
import com.volley.VolleyError;


public class Core{
    private Context context;
    public static final String TAG = "FNCore";
    private static Core instance;
    private NetworkExecutor networkExecutor;
    public Core init(Context context){
    	this.context = context;
    	networkExecutor = NetworkExecutor.getInstance().init(context);
    	return this;
    }
    
    public static Core getInstance(){
    	synchronized (Core.class) {
			if (instance == null) {
				instance = new Core();
			}
		}
    	return instance;
    }
    
    public void cancelAllRequest(String tag){
    	if(networkExecutor != null){
    		networkExecutor.cancelRequestsByTag(tag);
    	}
    }
    
    public void getConfigurations(String tagRequest,final GotConfigurationsCallback configurationsCallback){
    	networkExecutor.getConfigurations(tagRequest,new Response.Listener<JSONObject>(){

			@Override
			public void onResponse(JSONObject response, String arg1) {
				if(configurationsCallback != null){
					Log.e("Response Success", response == null?"Response NULL":"Got Response.");
					if(response != null){
						ArrayList<Configurations> configs = new ArrayList<Configurations>();
						try {
							JSONArray arr = response.getJSONArray("data");
							Configurations config = null;
							JSONObject jsonObj;
							String message = null;
							String[] splitter;
							String encodedGroup,normalGroup,enLocale = null;
							DummyAlg da= new DummyAlg(Constants.DIGEST_STRING, Constants.DUMMY_STRING);
							//[cf]udName:currentVer:udpid:expression@ud_title(not encoded):description(not encoded)
							for(int i=0;i<arr.length();i++){
								jsonObj = arr.getJSONObject(i);
								config = new Configurations();
								message = jsonObj.getString("message");
								if(!message.startsWith("[cf]")){
									continue;
								}
								message = message.substring(4);
								splitter = message.split("@");
								encodedGroup = splitter[0];//encoded
								normalGroup = splitter[1];
								if(splitter.length>=3){
									enLocale = splitter[2];
								}
								splitter = normalGroup.split(":");
								config.udTitle = splitter[0];
								config.description = splitter[1];
								try {
									encodedGroup = new String(da.decrypt(encodedGroup));
									splitter = encodedGroup.split(":");
									if(splitter.length>3){
										config.udName = splitter[0];
										config.currentVer = splitter[1];
										config.udPId = splitter[2];
										config.expression = splitter[3];
									}
									if(!TextUtils.isEmpty(enLocale)){
										splitter = enLocale.split(":");
										config.udTitle_en = splitter[0];
										config.description_en = splitter[1];
									}
								} catch (Exception e) {
									e.printStackTrace();
								}
								configs.add(config);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
						configurationsCallback.onGotConfigurations(configs);
					}else{
						configurationsCallback.onGotConfigurations(null);
					}
				}
			}
    		
    	}, new Response.ErrorListener(){

			@Override
			public void onErrorResponse(VolleyError arg0, String arg1) {
				configurationsCallback.onGotConfigurations(null);
			}
    		
    	});
    }
    
    public void getNotifications(String tagRequest,String pid,final String filter,final GotNotificationsCallback notificationCallback){
    	networkExecutor.getNotifications(tagRequest,pid,filter,new Response.Listener<JSONObject>(){

			@Override
			public void onResponse(JSONObject response, String arg1) {
				if(notificationCallback != null){
					Log.e("Response Success", response == null?"Response NULL":"Response Noti success");
					if(response != null){
						ArrayList<Notification> notifications = new ArrayList<Notification>();
						try {
							JSONArray arr = response.getJSONArray("data");
							Notification notification = null;
							JSONObject jsonObj;
							String message = null;
							String[] splitter;
							String id,title,content,link,photoUrl,expireDate;
							DummyAlg da= new DummyAlg(Constants.DIGEST_STRING, Constants.DUMMY_STRING);
							for(int i=0;i<arr.length();i++){
								jsonObj = arr.getJSONObject(i);
								notification = new Notification();
								message = jsonObj.getString("message");
								message = message.substring(TextUtils.isEmpty(filter)?0:filter.length()+2);
								splitter = message.split("@");
								if(TextUtils.isEmpty(message)|| splitter.length==0){
									continue;
								}
								id = splitter[0];//encoded
								title = splitter[1];
								content = splitter[2];
								link = splitter[3];
								photoUrl = splitter[4];
								expireDate = splitter[5];
								boolean  isExpired = Utils.isExpired(Long.parseLong(expireDate));
								if(!isExpired){
									notification.id = id;
									notification.title = title;
									try {
										if(!TextUtils.isEmpty(link)){
											notification.link = new String(da.decrypt(link));
											notification.link = notification.link.replace(" ", "");
										}
										if(!TextUtils.isEmpty(photoUrl)){
											notification.photoUrl = new String(da.decrypt(photoUrl));
											notification.photoUrl = notification.photoUrl.replace(" ", "");
										}
									} catch (Exception e) {
										e.printStackTrace();
									}
									notification.content = content;
									notification.expireDate = expireDate;
									notifications.add(notification);
								}else{
									Log.e("Notification","Got one expired :"+Utils.convertUnixtimeToDate(Utils.convertUnixtimeToDate(Long.parseLong(expireDate))));
									return;
								}
							}
							notificationCallback.onGotNotification(notifications);
						} catch (JSONException e) {
							e.printStackTrace();
							notificationCallback.onGotNotification(null);
						}
					}else{
						notificationCallback.onGotNotification(null);
					}
				}
			}
    		
    	}, new Response.ErrorListener(){

			@Override
			public void onErrorResponse(VolleyError arg0, String arg1) {
				
			}
    		
    	});
    }
    
    ////
//    new Response.Listener<JSONObject>(){
//
//		@Override
//		public void onResponse(JSONObject arg0, String arg1) {
//			
//		}
//		
//	}, new Response.ErrorListener(){
//
//		@Override
//		public void onErrorResponse(VolleyError arg0, String arg1) {
//			
//		}
//		
//	}
    ////
    public void cancelRequestsByTag(String tag){
    	if(networkExecutor != null){
    		networkExecutor.cancelRequestsByTag(tag);
    	}
    }
    
}
